//
//  GitHubNetworkService.swift
//  SwiftRx研究
//
//  Created by 世霖 on 2020/7/20.
//  Copyright © 2020 世霖. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class GitHubNetworkService  {
    
//    验证用户是否存在
    func usernameAvailable(_ username: String) -> Observable<Bool> {
        let url = URL(string: "https://github.com/\(username.URLEscaped)")!
             let request = URLRequest(url: url)
        return  URLSession.shared.rx.response(request: request).map { pair  in
            return pair.response.statusCode == 404
        }
    .catchErrorJustReturn(false)
    }

    //注册用户
     func signup(_ username: String, password: String) -> Observable<Bool> {
         //这里我们没有真正去发起请求，而是模拟这个操作（平均每3次有1次失败）
         let signupResult = arc4random() % 3 == 0 ? false : true
         return Observable.just(signupResult)
             .delay(1.5, scheduler: MainScheduler.instance) //结果延迟1.5秒返回
     }
    
}

extension String {
       //字符串的url地址转义
     var URLEscaped: String {
         return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? ""
     }
    
}
